/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package horsechess.server.data;

import horsechess.server.gui.GUIServer;
import horsechess.util.Status;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;

/**
 *
 * @author Administrator
 */
public class RoomManager implements Subject {

    private String roomName;
    public ArrayList<ClientHandler> clients;
    private boolean full = false;
    private GUIServer uIServer;
    private int time = 15;
    private Timer timer;
    private Timer gameOverTimer;
    private int matchTime = 420;

    public RoomManager(String roomName, GUIServer server) {
        clients = new ArrayList(4);
        this.roomName = roomName;
        this.uIServer = server;
        timer = new Timer(1000, new TickClock());
        gameOverTimer = new Timer(1000, new GameOver());
    }

    public void registerClient(ClientHandler client) {
        if (!clients.contains(client)) {
            clients.add(client);
        }
        if (clients.size() == 4) {
            full = true;
        }
    }

    public class TickClock implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            time--;
            if (time == 0) {
                broadcastMesage("@Clock#Timeout!!!");
                timer.stop();
            } else {
                broadcastMesage("@Clock#Time: " + time);
            }
        }
    }

    public class GameOver implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            matchTime--;
            if (matchTime == 0) {
                broadcastMesage("@MatchTime#Timeout!!");
                gameOverTimer.stop();
                timer.stop();
            } else {
                broadcastMesage("@MatchTime#Time of match: " + matchTime);
            }
        }
    }

    public void stop() {
        timer.stop();
    }

    public void restart() {
        if (time != 15) {
            time = 15;
        }
        if (timer.isRunning()) {
            timer.stop();
        }
        timer.start();
    }

    public String getRoomName() {
        return roomName;
    }

    public boolean isFull() {
        return full;
    }

    public boolean disconnectAllPlayers() {
        boolean isSuccess = true;
        broadcastMesage(Status.toString(Status.SHUT_DOWN));
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler clientHandler = clients.get(i);
            try {
                // clientHandler.send(clientHandler.player.toString() + "#SHUTDOWNSERVER");
                clientHandler.socket.close();
                removeClient(clientHandler);
            } catch (IOException ex) {
                isSuccess = false;
                registerClient(clientHandler);
            }
        }
        return isSuccess;
    }

    public boolean isHasInfo() {
        boolean temp = true;
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            if (client.player == null) {
                temp = false;
            }
        }
        return temp;
    }

    public void removeClient(ClientHandler client) {
        int i = clients.indexOf(client);
        if (i >= 0) {
            clients.remove(client);
        }
    }

    public ArrayList getLoser(String winner) {
        ArrayList losers = new ArrayList(3);
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            if (!client.getName().equalsIgnoreCase(winner)) {
                losers.add(client);
            }
        }
        return losers;
    }

    public void startGame() {
        List<RoomManager> rooms = ServerHandler.listOfRoom;
        for (int i = 0; i < rooms.size(); i++) {
            RoomManager roomManager = rooms.get(i);
            if (roomManager.clients.size() > 1 && roomManager.isHasInfo()) {
                //roomManager.broadcastMesage("@Dice#" + 1);
                uIServer.btnPlay.setEnabled(true);
                uIServer.txtServerStatus.setText("There are " + roomManager.clients.size() + " player at room: " + getRoomName() + " are playing. !!!!");

                roomManager.handleDice();
                //status = Status.START_GAME;
                gameOverTimer.start();
                roomManager.broadcastMesage(Status.toString(Status.START_GAME));
//                for (int j = 0; j < roomManager.clients.size(); j++) {
//                    ClientHandler clientHandler = roomManager.clients.get(j);
//                    System.out.println("Position Player:" + clientHandler.player.getPosOfPlayer());
//                    clientHandler.status = Status.PLAYING;
//                    if (clientHandler.player.getPosOfPlayer() == 0) {
//                        clientHandler.send(Status.toString(Status.YOUR_TURN));
//                        clientHandler.status = Status.YOUR_TURN;
//                    } else {
//                        clientHandler.send(Status.toString(Status.OTHER_TURN));
//                        clientHandler.status = Status.OTHER_TURN;
//                    }
//                }
            }
        }

    }

    public void handleDice() {
        if (uIServer.radOneDice.isSelected()) {
            this.broadcastMesage("@Dice#1");
        }
        if (uIServer.radTwoDice.isSelected()) {
            this.broadcastMesage("@Dice#2");
        }
    }

    /**
     * Send to all player
     * @param msg
     */
    public void broadcastMesage(String msg) {
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            // System.out.println(msg);
            client.send(msg);
        }
    }

    public void broadcastInfoAllPlayerInRoom() {
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            broadcastMesage(client.player.toRoom());
        }

    }

    public ClientHandler getClient(String name) {
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            if (client.getName().equalsIgnoreCase(name)) {
                return client;
            }
        }
        return null;
    }

    /**
     * Send to all player, except playerPos
     */
    public void broadcastMessage(String msg, String playerName) {
        for (int i = 0; i < clients.size(); i++) {
            ClientHandler client = (ClientHandler) clients.get(i);
            if (!client.player.getPlayerName().equalsIgnoreCase(playerName)) {
                client.send(msg);
            }
        }
    }

    /**
     * Join vao mac dinh la` room one.
     */
    public void advertiseRoom() {

        broadcastMesage("@Room-" + ServerHandler.listOfRoom.get(0).getRoomName() + "-" + ServerHandler.listOfRoom.get(1).getRoomName());

    }

    public String getMessage(Status status, ClientHandler player) {
        switch (status) {
            case WAITING:
                return "Server is waiting for client connection";
            // Server begin to made the connect with client though TCP
            //case BEGIN_CONNECT: return "Server is starting to connect to client";
            case CONNECTED:
                return "Room has been connected with " + player.getName();
            case RESTART:
                return "Server is restarting";
            case PLAYING:
                return player.getName() + " is playing";
            case DISCONNECTING:
                return player.getName() + "is requiring to disconnect with " + roomName;
            case DISCONNECTED:
                return player.getName() + " was disconnected";
            default:
                return "There was exception occured on the server";
        }
    }
}
